﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.IO;

namespace SEORank
{
    /// <summary>
    /// Http助手
    /// </summary>
    public static class HttpHelper
    {
        //private static HttpClient client = new HttpClient() { BaseAddress = new Uri("https://www.baidu.com/") };

        //public static Get(string url)
        //{
        //}

        /// <summary>
        /// 通过IP138判断当前所在的IP
        /// </summary>
        /// <returns></returns>
        public static IpAddress GetIP(Proxy proxy = null)
        {
            string error = "";
            string html = Get("http://1212.ip138.com/ic.asp", out error, proxy);
            //string html = Get("http://www.whatismyip.com.tw/", out error, proxy);

            if (!string.IsNullOrWhiteSpace(error) || !html.Contains("来自：")) return null;

            //string ip = "";
            //ip = html.Substring(html.IndexOf("您的IP是：[") + 7, html.IndexOf("] 来自：") - html.IndexOf("您的IP是：[") - 7);
            //ip = html.Substring(html.IndexOf("<h2>") + 4, html.IndexOf("</h2>") - html.IndexOf("<h2>") - 4);

            IpAddress ip = new IpAddress()
            {
                IP = html.Substring(html.IndexOf("您的IP是：[") + 7, html.IndexOf("] 来自：") - html.IndexOf("您的IP是：[") - 7),
                Address = html.Substring(html.IndexOf("] 来自：") + 5, html.IndexOf("</center>") - html.IndexOf("] 来自：") - 5)
            };

            return ip;
        }

        /// <summary>
        /// 获取指定的URL内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string Get(string url, out string error, Proxy proxy = null)
        {
            error = "";
            string html = "";

            GC.Collect();
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream stream = null;
            StreamReader streamReader = null;

            try
            {
                request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Timeout = 20000;
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";

                if (proxy != null)
                {
                    request.Proxy = new WebProxy(proxy.Host, proxy.Port);
                }

                request.AllowAutoRedirect = true;
                request.KeepAlive = true;

                response = (HttpWebResponse)request.GetResponse();

                stream = response.GetResponseStream();

                if (stream != null)
                {
                    Encoding encoding = Encoding.Default;

                    switch (response.ContentType.Replace(" ", "").Trim().ToLower())
                    {
                        case "text/html;charset=utf-8":
                            encoding = Encoding.UTF8;
                            break;
                        default:
                            encoding = Encoding.Default;
                            break;
                    }

                    streamReader = new StreamReader(stream, encoding);
                }

                if (streamReader != null)
                {
                    html = streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                error = "ERROR:" + ex.Message;
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                    response.Dispose();
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                    streamReader.Dispose();
                }
            }

            return html;
        }
    }
}
